<template>
  <div class="app-container">
    <div class="filter-container">
<!--      <span>父组件的值：{{idListStr}}</span>-->
      <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-download" @click="handleBackups">
        下载备份
      </el-button>
      <el-upload action="/"
                 ref="upload"
                 accept=".txt"
                 :before-upload="beforeUpload"
                 :disabled="this.fileList.length !== 0"
                 :default-file-list="this.fileList"
      >
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search"
                   :disabled="this.fileList.length !== 0">上传备份（*.TXT）
        </el-button>
      </el-upload>
      <el-button :disabled="this.fileList.length == 0" v-waves class="filter-item" size="small" type="primary"
                 icon="el-icon-upload" @click="handleInsertBackups">
        插入备份
      </el-button>

    </div>


  </div>
</template>

<script>
  import {fetchBankupByIds,insertBankup} from './api'
  import waves from '@/directive/waves' // waves directive

  export default {
    name: 'TmptBankupRestore',
    directives: { waves },
    props: {
      //备份表的id
      idListStr: '',
      isFromFather: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        //上传的file
        fileList: [],
        fileListStr: ''
      }
    },

    created() {
      const clientHeight = `${document.documentElement.clientHeight}`//获取浏览器可视区域高度
      this.tableHeight = clientHeight - 350
    },
    beforeCreate() {
      // 读取文件
      FileReader.prototype.reading = function({ encode } = pms) {
        let bytes = new Uint8Array(this.result)    //无符号整型数组
        let text = new TextDecoder(encode || 'UTF-8').decode(bytes)
        return text
      }
      /* 重写readAsBinaryString函数 */
      FileReader.prototype.readAsBinaryString = function(f) {
        if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
        {
          this.onload = e => {  //在this.onload函数中，完成公共处理
            let rs = this.reading()
            console.log(rs)

          }
        }
        this.readAsArrayBuffer(f)  //内部会回调this.onload方法
      }
    },
    methods: {
      handleInsertBackups() {
        insertBankup({ 'fileListStr': this.fileListStr }).then(result => {
          if (result.success) {
            // this.getList()
            this.$notify({
              title: '成功',
              message: 'Insert Successfully',
              type: 'success',
              duration: 2000
            })
            // 从父组件调用此方法，进行回调下
            if (this.isFromFather) {
              this.$emit('insertFileResult')
            }
          }
        })

      },

      handleBackups() {
        if(this.idListStr==""){
          alert('请在主页面选择备份表')
          return;
        }
        fetchBankupByIds({ 'idListStr': this.idListStr }).then(result => {
          const items = result.list
          this.onClickDownDaily('tmpt_data_bankups.txt', items)
        })

      },
      onClickDownDaily(name, val) {
        let s = JSON.stringify(val)
        var export_blob = new Blob([s])
        var save_link = document.createElement('a')
        save_link.href = window.URL.createObjectURL(export_blob)
        save_link.download = name
        this.fakeClick(save_link)
      },
      fakeClick(obj) {
        var ev = document.createEvent('MouseEvents')
        ev.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        )
        obj.dispatchEvent(ev)
      },
      beforeUpload(file) {
        this.fileList = [file]
        // console.log('选择了文件beforeUpload')
        // 读取数据
        this.read(file)
        return false
      },
      read(f) {
        let rd = new FileReader()
        const _this = this
        _this.fileListStr = ''
        rd.onload = e => {
          //this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
          let cont = rd.reading({ encode: 'utf-8' })
          console.log(cont)
          _this.fileListStr = cont
          // let formerData = this.textData
          // this.textData = formerData + '\n' + cont
        }
        rd.readAsBinaryString(f)
      },
    }

  }
</script>

<style>
  .sortable-ghost {
    opacity: .8;
    color: darkgreen !important;
    background: #42b983 !important;
  }
</style>

<style scoped>
  .icon-star {
    margin-right: 2px;
  }

  .drag-handler {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }

  .show-d {
    margin-top: 15px;
  }
</style>
